package com.hsgene.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.check.ObjectAttrUtils;
import com.hsgene.common.util.http.HttpConnectionManager;
import com.hsgene.message.persistence.TripartiteRequestRepository;
import com.hsgene.message.service.TripartiteRequestService;
import com.hsgene.mq.outsystem.SystemOutMQInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * TripartiteRequestServiceImpl
 *
 * @author wxf
 * @date 2018/12/11 17:47
 **/
@Service
public class TripartiteRequestServiceImpl implements TripartiteRequestService {

    private static Logger LOGGER = LogManager.getLogger(TripartiteRequestServiceImpl.class);

    @Resource
    private TripartiteRequestRepository requestRepository;

    @Resource
    private HttpConnectionManager httpConnectionManager;

    /**
     * 发送机构订单信息
     *
     * @param orderId 订单ID
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public String sendAgencyOrderInfo(String orderId) {
        List<SystemOutMQInfo> agencyOrderInfos = requestRepository.getAgencyOrderInfo(orderId);
        if (agencyOrderInfos == null || agencyOrderInfos.isEmpty()) {
            return null;
        }
        //推送机构信息
        startSendAgencyOrderInfo(agencyOrderInfos);
        return "ok";
    }

    /**
     * 发送重试
     * 每天凌晨2点定时
     */
    //@Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(fixedDelay = 5000)
    protected void retrySendAgency() {
        List<SystemOutMQInfo> agencyOrderInfos = requestRepository.getSendFailedAgencyOrderInfo();
        if (agencyOrderInfos == null || agencyOrderInfos.isEmpty()) {
            return;
        }
        //推送机构信息
        startSendAgencyOrderInfo(agencyOrderInfos);
    }

    private void startSendAgencyOrderInfo(List<SystemOutMQInfo> agencyOrderInfos) {
        try {
            for (SystemOutMQInfo orderInfo : agencyOrderInfos) {
            /*orderInfo.setItemName("HS0001");
            orderInfo.setSampleTypeCode("BE");
            orderInfo.setSampleType("全血（外周血BD管抗凝）");*/
                if (StringUtils.isEmpty(orderInfo.getAgencyUrl())) {
                    LOGGER.warn("send agency url is null,agencyId is:" + orderInfo.getAgencyId());
                    continue;
                }
                List<NameValuePair> valuePairs = ObjectAttrUtils.objectAttrToNameValuePair(orderInfo, "agencyUrl",
                        "orderId", "agencyId");
                LOGGER.info("start send agency order，orderId :" + orderInfo.getOrderId());
                String result = httpConnectionManager.doPost(valuePairs, orderInfo.getAgencyUrl(), CharactersConstant
                        .UTF_8);
                JSONObject jsonObject = JSONObject.parseObject(result);
                int size = jsonObject.keySet().size();
                Boolean sendResult = jsonObject.getBoolean("success");
                //true表示推送成功,更新订单表示已推送
                if (sendResult) {
                    LOGGER.info("send agency order is success,success orderId :" + orderInfo.getOrderId() + "," +
                            "agencyId " +
                            "is:" + orderInfo.getAgencyId());
                    requestRepository.updateOrderIsSend(orderInfo.getOrderId(), orderInfo.getAgencyId(), 1);
                }
                //返回false，且size为1，说明推送数据问题
                else if (!sendResult && size == 1) {
                    LOGGER.error("send agency order is failed,failed orderId :" + orderInfo.getOrderId() + ",agencyId" +
                            " " +
                            "is:" + orderInfo.getAgencyId());
                    requestRepository.updateOrderIsSend(orderInfo.getOrderId(), orderInfo.getAgencyId(), 2);
                } else {
                    LOGGER.error("send agency order data is error,failed orderId :" + orderInfo.getOrderId() + "," +
                            "agencyId" +
                            "is:" + orderInfo.getAgencyId());
                    requestRepository.updateOrderIsSend(orderInfo.getOrderId(), orderInfo.getAgencyId(), 3);
                }
            }
        } catch (Exception e) {
            LOGGER.error("send Agency OrderInfo is error...", e);
        }
    }
}
